from django.contrib.auth.backends import ModelBackend
from users.models import User
from django.db.models import Q
from meiduo_mall.utils.secret import SecretOauth
from django.conf import settings


# 新建类，继承自 ModelBackend
class UsernameMobileAuthBackend(ModelBackend):

    # 重写认证 authenticate( ) 方法
    def authenticate(self, request, username=None, password=None, **kwargs):

        # 分别使用用户名和手机号查询用户
        # 返回查询到的用户实例
        # select * from tb_users where username="" or mobile=""
        try:
            user = User.objects.get(Q(username=username) | Q(mobile=username))
        except User.DoesNotExist as e:
            return None
        print(user)
        if user.check_password(password):
            return user


# 　获取验证邮件完成的verify_url
def generate_verify_email_url(request):
    """
    :param request: 请求对象－－通过请求对象获取登陆的用户request.user
    :return: 完整的verify_url
    """
    # 1. 获取当前登陆的用户
    user = request.user
    data_dict = {
        "user_id": user.id,
        "email": user.email
    }
    auth = SecretOauth()
    token = auth.dumps(data_dict)
    verify_url = settings.EMAIL_VERIFY_URL + token

    return verify_url